package com.itheima.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Author: Zheng
 * Date:   2024/3/16  17:28
 * Package：com.itheima.filter
 * Description：
 * Version：1.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * @description： 自定义权限过滤器业务逻辑，exchange：请求响应对象，chain：过滤器链
     * @date：2024/3/16  17:54
     * @return：
     **/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取地址栏普通第一个请求参数
        String authorization = request.getQueryParams().getFirst("authorization");
        //如果判断是否有值，并且是否为admin
        if (StringUtils.isNotEmpty(authorization) && authorization.equals("admin")) {
            //符合条件，放行
            return chain.filter(exchange);
        }
        //反之，设置响应状态码，401 权限不足
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //结束响应
        return response.setComplete();
    }

    /**
     * @description： 设置过滤器执行的优先级
     * @date：2024/3/16  17:53
     * @return：
     **/
    @Override
    public int getOrder() {
        //值越小，执行的的优先级越高
        return -1;
    }
}
